// Memory Game

function showGame() {

	var top = 110;
	var id = 0;
	for ( r = 0; r < 4 ; r++ ) {
		var left = 10;
		for ( c = 0; c < 4; c++ ) {
			style = "left:" + left + "px;top:" + top + 
					"px;position:absolute;width:100px;height:100px;border:1px solid #000;";
			topStyle = style + "background-color: #FDD017;z-index: 1";
			bottomStyle = style + "background-color: #FFF";
			document.write("<div class=\"cell\" id=\"top_" + id + "\" style=\"" + topStyle + "\" onclick=\"showBottom('" + id + "')\"></div>");
			document.write("<div class=\"cell\" id=\"bottom_" + id + "\" style=\"" + bottomStyle + "\"></div>");
			left += 101;
			id++;
		}
		top += 101;
	}
}

function getMatch(id) {

	var matches = document.gamef.matches.value;
	var pairs = matches.split(";");
	for( i = 0; i < pairs.length; i++ ) {
		var pair = pairs[i].split(",");
		if ( pair[0] == id ) {
			return pair[1];
		} else if ( pair[1] == id ) {
			return pair[0];
		}
	}
	return "";
}

function setMatch(idx1,idx2) {

	if ( document.gamef.matches.value != "" ) {
		document.gamef.matches.value += ";";
	}
	document.gamef.matches.value += idx1 + "," + idx2;
}

function hideTop(id,vis) {
	setVisibility("top_" + id,vis);
}

function showBottom(id) {

	hideTop(id,"hidden");
 		
	if ( document.gamef.pick.value != "" &&
		 document.gamef.pick.value != getMatch(id) ) {
		setTimeout("hideTop('" + document.gamef.pick.value + "','visible')",1000);
		setTimeout("hideTop('" + id + "','visible')",1000);
	} 

	if ( document.gamef.pick.value == "" ) {
		document.gamef.pick.value = id;
	} else {
		document.gamef.pick.value = "";
	}
}

function fillGame() {
	post(fillCells,"memory.php",null);	
}

function reset() {
	
	document.gamef.pick.value = "";
	document.gamef.matches.value = "";
	for ( i = 0; i < 16; i++ ) {
		hideTop(i,"visible");
	}
}

function fillCell(cells,val) {
	
	var idx = Math.floor(Math.random()*16);
	while ( cells[idx] != null ) {
		idx = Math.floor(Math.random()*16);
	}
	cells[idx] = val;
	document.getElementById('bottom_' + idx).innerHTML = val;
	return idx;
}

function fillCells() {
	
	if (xmlHttp.readyState == 4) {
		reset();
		var pairs = xmlHttp.responseText.split(";");
		var cells = [];
		for ( i = 0; i < pairs.length; i++ ) {
			var pair = pairs[i].split(",");
			var eIdx = fillCell(cells,pair[0]);
			var kIdx = fillCell(cells,pair[1]);
			setMatch(eIdx,kIdx);
		}
	}
}
